/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.springWebTestNG.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author zhou.zhefu
 */
public class FutureTaskEmulator {
    private FutureTask<TheData> future = new FutureTask<TheData>(new Callable<TheData>() {
        @Override
        public TheData call() throws Exception {
            Thread.sleep(2000);
            return new TheData(1001);
        }
    });
            
    private class TheData {
        int id;

        public TheData(int id) {
            this.id = id;
        }
        
        @Override
        public String toString() {
            return "TheData[" + id + "]";
        }
    }  
    
    public void start() throws Exception {
        new Thread(future).start();
        
        try {
            //retrieve TheData once it is prepared by 'future'
            TheData result = future.get();
            
            System.out.println(result + " was processed.");
        } catch (InterruptedException ex) {
            Logger.getLogger(FutureTaskEmulator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Throwable t = ex.getCause();
            if (t instanceof RuntimeException) {
                throw ex;
            } else if (t instanceof Error) {
                throw ex;
            } else {
                throw new IllegalStateException("Not unchecked", t);
            }
        }
    }
    
}
